// pagination-select
import type { App } from "vue";
export const selectInfinite = (app: App) => {
  app.directive("select-infinite", {
    mounted(el, binding) {
      // 获取选择器元素
      const SELECT_DOM = el.querySelector(
        ".el-select-dropdown .el-select-dropdown__wrap"
      );
      // 确保元素存在
      if (!SELECT_DOM) {
        console.warn("未找到滚动容器元素");
        return;
      }
      // 滚动事件处理函数
      const handleScroll = function () {
        const isAtTop = this.scrollTop === 0;
        const isAtBottom =
          this.scrollHeight - Math.ceil(this.scrollTop) <= this.clientHeight;

        // 滚动到顶部
        if (isAtTop) {
          binding.value("subtract");
        }

        // 滚动到底部
        if (isAtBottom) {
          binding.value("add");
        }
      };

      // 鼠标滚轮事件处理函数
      const handleWheel = function (event) {
        const isAtTop = this.scrollTop === 0;
        const isAtBottom =
          this.scrollHeight - Math.ceil(this.scrollTop) <= this.clientHeight;

        // 向上滚动且已在顶部
        if (isAtTop && event.deltaY < 0) {
          binding.value("subtract");
        }

        // 向下滚动且已在底部
        if (isAtBottom && event.deltaY > 0) {
          binding.value("add");
        }
      };

      // 添加事件监听
      SELECT_DOM.addEventListener("scroll", handleScroll);
      SELECT_DOM.addEventListener("wheel", handleWheel);

      // 在元素上存储事件处理函数，以便在卸载时移除
      SELECT_DOM._scrollHandlers = {
        handleScroll,
        handleWheel,
      };
    },
    // 添加 unmounted 钩子以清理事件监听，防止内存泄漏
    unmounted(el) {
      const SELECT_DOM = el.querySelector(
        ".el-select-dropdown .el-select-dropdown__wrap"
      );
      if (SELECT_DOM && SELECT_DOM._scrollHandlers) {
        const { handleScroll, handleWheel } = SELECT_DOM._scrollHandlers;
        SELECT_DOM.removeEventListener("scroll", handleScroll);
        SELECT_DOM.removeEventListener("wheel", handleWheel);
        delete SELECT_DOM._scrollHandlers;
      }
    },
  });
};
